# -*- encoding: utf-8 -*-
"""
Copyright (c) 2023 - present SKbioinfo
"""
from apps import db
from apps.API.auth.util import hash_pass
from flask_login import UserMixin
import datetime as dt
from apps.API.electricSigature.AuditRecord import Part11AuditRecord
from werkzeug.security import generate_password_hash, check_password_hash
import json

class Users(db.Model, UserMixin):
    
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True)
    email = db.Column(db.String(64), unique=True)
    role_id = db.Column(db.String(64),db.ForeignKey('roles.name'))
    create_time = db.Column(db.DateTime, default=lambda: dt.now())
    password = db.Column(db.LargeBinary)
    # is_active = db.Column(db.Boolean, default=True)
    # public_key = db.Column(db.Text)  # 存储用户的公钥PEM格式

    def __init__(self, **kwargs):
      
        for property, value in kwargs.items():
            # depending on whether value is an iterable or not, we must
            # unpack it's value (when **kwargs is request.form, some values
            # will be a 1-element list)
            if hasattr(value, '__iter__') and not isinstance(value, str):
                # the ,= unpack of a singleton fails PEP8 (travis flake8 test)
                value = value[0]
            if property == 'password':
                value = hash_pass(value)
            setattr(self, property, value)

    def __repr__(self):
        return str(self.username)
    
    def to_dict(self):
        result = {}
        for c in self.__table__.columns:
            value = getattr(self, c.name)
            if isinstance(value, dt.datetime):
                value = value.strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(value, dt.date):
                value = value.strftime('%Y-%m-%d')
            result[c.name] = value
        return result
    
    def init_user():
        Admin={"id":1,"username":"admin","email":"94405171@qq.com","role_id":"R990","password":"123"}
        user_id=Admin["username"] + "_" + str(Admin["id"])
        # 1. 创建用户并生成密钥对
        Part11AuditRecord.audit_add_user(
            user_id=user_id, 
            name=Admin["username"],
            role=Admin["role_id"], 
            password=Admin["password"]
        )
        # 2. 创建记录
        Part11AuditRecord.create_sign_record(
            record_id="DOC-1",
            record_type="USER_CREATE",
            content="Create User admin",
            created_by=user_id,
            password=Admin["password"],
            passd_check=True
        )
        User=Users.query.filter_by(username=Admin["username"]).first()
        if User is None:
            print("##### Creating Admin account ####")
            user=Users(username=Admin["username"])
            user.email=Admin["email"]
            user.role_id=Admin["role_id"]
            user.password=hash_pass(Admin["password"])
            db.session.add(user)
            db.session.commit()
        else:
            pass

class Role(db.Model):
    # 定义Role的数据库模型
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    # 该用户角色的Role_id
    name = db.Column(db.String(64), unique=True)
    # 该用户角色的名称
    detail = db.Column(db.String(64))
    # 该用户角色对应的权限
    permissions = db.Column(db.String(2048))
    # 该用户角色是否为默认
    default = db.Column(db.Boolean, default=False, index=True)
    # 该用户的组别
    group = db.Column(db.String(64))
    # 角色为该用户角色的所有用户
    users = db.relationship('Users', backref="role",lazy='dynamic')
    @staticmethod
    def init_role():
        print("初始化Role信息！")
        roles = {
            'R001': ('1,2,3,4,5,6' , False, "ProjectManager","NGS"),
            'R002': ('1,2,3,4,5,6', False,"Bio","NGS"),
            'R990': ('15', False,"SuperManager", "Super")
        }
        #除了onlyquery之外，其他的都是模式false
        for r in roles:
            role = Role.query.filter_by(name=r).first()
            if role is None:
                # 如果用户角色没有创建: 创建用户角色
                role = Role(name=r)
                role.permissions = roles[r][0]
                role.default = roles[r][1]
                role.detail = roles[r][2]
                role.group = roles[r][3]
                db.session.add(role)
                db.session.commit()
            else:
                pass
    def add_permission(self, perm):
        if not self.has_permission(perm):
            self.permissions += perm

    def remove_permission(self, perm):
        if self.has_permission(perm):
            self.permissions -= perm

    def reset_permissions(self):
        self.permissions = 0

    def has_permission(self, perm):
        return self.permissions & perm == perm

    def __repr__(self):
        return '<Role %r>' % self.name
       
    def to_dict(self):
        result = {}
        for c in self.__table__.columns:
            value = getattr(self, c.name)
            if isinstance(value, dt.datetime):
                value = value.strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(value, dt.date):
                value = value.strftime('%Y-%m-%d')
            result[c.name] = value
        return result
